package ZookeeperTest;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;


public class DistributeLock {
    private static int count=10;//10个产品
    static  InterProcessMutex lock;
    public static void main(String[] args) {
        //定义客户端的重试策略
        ExponentialBackoffRetry policy = new ExponentialBackoffRetry(1000, 10);
        //创建ZK客户端（第二种方法）
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("bigdata211:2181,bigdata212:2181,bigdata213:2181")
                .retryPolicy(policy)
                .build();
       //开启客户端，在zk客户端创建锁
        client.start();
        lock = new InterProcessMutex(client, "/myLock");
        //启动线程访问共享资源
        for (int i = 0; i <50 ; i++) {//创建50个线程
            Customer s = new Customer();
            if(count<=0){
                System.out.println("商品抢完了");
                break;
            }
             s.run();

        }
    }

    protected static void printCountNum() throws InterruptedException {
            System.out.println("**********"+Thread.currentThread().getName()+"***********");
            count--;
            System.out.println("剩余iPad数为" + count);
            System.out.println("**********" + Thread.currentThread().getName() + "***********");
            Thread.sleep(100);

    }

}
class Customer extends Thread{
    @Override
    public void run() {
        try {
            //获取锁
            DistributeLock.lock.acquire();
            //访问并访问打印共享资源
            DistributeLock.printCountNum();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                //释放锁
                DistributeLock.lock.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}